package java_thinking.unit_21._21_6;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Desc:   6-8 支持关闭操作的 web 服务器
 * @author: cww
 * @DateTime: 2019/6/11 19:02
 */

public class LifecycleWebServer {
    /**
     * newCachedThreadPool 可缓存的线程池，如果线程池的当前规模超过了处理需求时，那么将回收空闲的线程，而当需求增加时
     * 则可以添加新的线程，线程池的规模不存在任何限制；
     */
    private final ExecutorService exec = Executors.newCachedThreadPool();
    public void start() throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (!exec.isShutdown()) {
            final Socket conn = socket.accept();
            exec.execute(new Runnable() {
                @Override
                public void run() {
                    handleRequest(conn);
                }
            });

        }
    }

    public void stop() {
        exec.shutdown();
    }
    void handleRequest(Socket connection) {
        Request req = readRequest(connection);
        if (isShutdownRequest(req))
            stop();
        else
            dispatchRequest(req);
    }
    interface Request {
    }

    private Request readRequest(Socket s) {
        return null;
    }
    private void dispatchRequest(Request r) {
    }
    private boolean isShutdownRequest(Request r) {
        return false;
    }

}
